import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/routes/consignment/detail/EcyConsignmentCommentPage.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ConsignProduct.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ConsignReply.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../EcyRouter.dart';
import '../../../constant/EcyEventConsnt.dart';
import '../../../ecycommon/EcyCommonWidgets.dart';
import '../../../ecycommon/EcyEventBus.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/ConsignComment.dart';

class EcyConsignmentDetailPage extends EcyCommonBaseWidget {
  late _EcyConsignmentDetailPageState state;
  late int productId;

  EcyConsignmentDetailPage({required super.key, required this.productId});

  @override
  State<EcyCommonBaseWidget> createState() {
    state = _EcyConsignmentDetailPageState(this.productId);
    return state;
  }
}

class _EcyConsignmentDetailPageState extends EcyCommonBaseWidgetState {
  late EcyCommonBaseWidget controller;
  late int productId;

  _EcyConsignmentDetailPageState(this.productId);

  final ScrollController _scrollController = ScrollController();
  bool _ownerFlag = false;
  final _talkController = TextEditingController();
  ConsignProduct _consignProduct = ConsignProduct();
  final List<String> _typeList = ["分类", "品牌", "成色", "是否有原包装"];
  final List<String> _finenessList = ["全新", "几乎全新", "轻微使用痕迹", "明显使用"];
  final List<String> _originalPackageList = ["  是  ", "  否  "];

  late EcyConsignmentCommentPage ecyConsignmentCommentPage;
  bool _loading = false;

  @override
  void initState() {
    super.initState();

    initNotis();

    ecyConsignmentCommentPage = EcyConsignmentCommentPage(
        key: consignmentCommentChildKey,
        productId: productId,
        onPressedCallback: (comment, reply) {
          _showModalBottomSheet(context, comment, reply);
        });

    _scrollController.addListener(_onScroll);

    requestData();
  }

  initNotis() {
    EcyEventBus().on(EcyEventConst.kLogined, (arg) {
      requestData();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      ecyConsignmentCommentPage.loadData(); // 加载更多数据的函数
    }
  }

  @override
  void requestData() async {
    super.requestData();

    Map<String, dynamic> body = {
      "productId": productId,
    };
    var response =
        await EcyRequestbasemanager().post("/app/api/app/consign/detail", body);
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        ConsignProduct consignProduct =
            ConsignProduct.fromJson(response["data"]);
        if(mounted) {
          setState(() {
            _ownerFlag = consignProduct.currentUser == '1';
            _consignProduct = consignProduct;
          });
        }
      }
    }
  }

  /// 删除
  void _deleteConsignProduct() async {
    try {
      var response = await EcyRequestbasemanager().post(
          "/app/api/app/consign/delete",
          {"productId": _consignProduct.productId});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EasyLoading.showToast("删除成功", duration: const Duration(seconds: 2));
        Navigator.pop(context, true);
        return;
      }
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 下架
  void _offlineShelf(int productId) async {
    try {
      var response = await EcyRequestbasemanager().post(
          "/app/api/app/consign/offlineAndOnline",
          {"productId": productId, "status": "3"});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EasyLoading.showToast("下架成功", duration: const Duration(seconds: 1));
        EcyRouter.pop(context, "");
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  Future<void> _orderCreate() async {
    if (_loading) {
      return;
    }

    setState(() {
      _loading = true;
    });

    try {
      var response = await EcyRequestbasemanager().post(
          "/app/api/app/consign/order/create",
          {"productId": _consignProduct.productId});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          Map<String, dynamic> dataMap = response["data"] as Map<String, dynamic>;
          EcyRouter.push(context, EcyRouter.myConsignmentOrderDetailPage,
              {"orderCode": dataMap['orderCode'], "type": "1"});
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_consignProduct == null) {
      return Container();
    }

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 50.w,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        titleSpacing: 0,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            _consignProduct.sellerAvatar == null
                ? Container()
                : SizedBox(
                    height: 30,
                    width: 30,
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: CachedNetworkImage(
                            imageUrl: _consignProduct.sellerAvatar ?? "",
                            imageBuilder: (context, imageProvider) => Container(
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.only(
                                          topRight: Radius.circular(8.r),
                                          topLeft: Radius.circular(8.r)),
                                      image: DecorationImage(
                                          image: imageProvider,
                                          fit: BoxFit.cover)),
                                ),
                            errorWidget: (context, url, error) =>
                                Image.asset("assets/images/app_icon.png"))),
                  ),
            const Padding(padding: EdgeInsets.only(right: 5)),
            Text(
              _consignProduct.sellerName ?? "",
              style: const TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        controller: _scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        child: Container(
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                  height: MediaQuery.of(context).size.width - 20,
                  width: MediaQuery.of(context).size.width,
                  child: PageView(
                    scrollDirection: Axis.horizontal,
                    reverse: false,
                    controller: PageController(
                        initialPage: 1, keepPage: false, viewportFraction: 1),
                    children: (_consignProduct.images ?? []).map((e) {
                      return CachedNetworkImage(
                          imageUrl: e.imageUrl ?? "",
                          imageBuilder: (context, imageProvider) => Container(
                                decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: imageProvider,
                                        fit: BoxFit.contain)),
                              ),
                          errorWidget: (context, url, error) =>
                              Image.asset("assets/images/app_icon.png"));
                    }).toList(),
                  )),
              Padding(
                padding: const EdgeInsets.all(12),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    RichText(
                        text: TextSpan(children: [
                      const TextSpan(
                        text: '￥',
                        style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 14,
                          color: Color(0xFFF55F4E),
                        ),
                      ),
                      TextSpan(
                          text: '${_consignProduct.price ?? 0.00}',
                          style: const TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 28,
                            color: Color(0xFFF55F4E),
                            leadingDistribution:
                                TextLeadingDistribution.even, // 设置leading策略
                          )),
                    ])),
                    const Padding(padding: EdgeInsets.only(bottom: 10)),
                    Text(_consignProduct.title ?? "",
                        style: const TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16,
                          color: Color(0xFF262626),
                          leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                        )),
                    const Padding(padding: EdgeInsets.only(bottom: 10)),
                    Text(_consignProduct.description ?? "",
                        style: const TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w500,
                          fontSize: 14,
                          color: Color(0xFF262626),
                          leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                        )),
                    const Padding(padding: EdgeInsets.only(bottom: 10)),
                    Text(
                        _consignProduct.createTime?.replaceFirst("T", " ") ??
                            "",
                        style: const TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w400,
                          fontSize: 12,
                          color: Color(0xFF8C8C8C),
                          leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                        )),
                    const Padding(padding: EdgeInsets.only(bottom: 20)),
                    SizedBox(
                      height: 50,
                      width: MediaQuery.of(context).size.width,
                      child: ListView.separated(
                        shrinkWrap: true,
                        physics: const AlwaysScrollableScrollPhysics(),
                        scrollDirection: Axis.horizontal, // 设置滚动方向为水平
                        itemCount: _typeList.length,
                        itemBuilder: (context, index) {
                          var item = _typeList[index];
                          var itemValue = index == 0
                              ? _consignProduct.categoryName
                              : index == 1
                                  ? _consignProduct.brandName
                                  : index == 2
                                      ? _finenessList[int.parse(
                                          _consignProduct.condition ?? "0")]
                                      : _originalPackageList[_consignProduct
                                                  .hasOriginalPackaging ??
                                              false
                                          ? 0
                                          : 1];
                          return Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                item,
                                style: const TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w500,
                                  fontSize: 12,
                                  color: Color(0xFF8C8C8C),
                                ),
                              ),
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 10)),
                              Text(
                                itemValue ?? "",
                                style: const TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w700,
                                  fontSize: 12,
                                  color: Color(0xFF262626),
                                ),
                              ),
                            ],
                          );
                        },
                        separatorBuilder: (BuildContext context, int index) {
                          return const VerticalDivider(thickness: 0.2);
                        },
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 20),
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text("自提点",
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 16,
                                    color: Color(0xFF262626))),
                            const Padding(padding: EdgeInsets.only(bottom: 8)),
                            Text(_consignProduct?.shop?.address ?? "***",
                                style: const TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14,
                                    color: Color(0xFF8C8C8C))),
                          ]),
                    ),
                    const Padding(padding: EdgeInsets.only(bottom: 20)),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("留言（${_consignProduct.commentCount ?? 0}）条",
                              style: const TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w700,
                                fontSize: 16,
                                color: Color(0xFF262626),
                                leadingDistribution:
                                    TextLeadingDistribution.even, // 设置leading策略
                              )),
                          GestureDetector(
                              behavior: HitTestBehavior.translucent,
                              onTap: () {
                                _showModalBottomSheet(context, null, null);
                              },
                              child: Row(
                                children: [
                                  Image.asset(
                                    "assets/images/ic_comments.png",
                                    width: 14.w,
                                    height: 14.w,
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(
                                      left: 2,
                                    ),
                                    child: Text(
                                      '回复',
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w500,
                                          fontSize: 14.sp,
                                          color: const Color(0xFF8C8C8C)),
                                    ),
                                  ),
                                ],
                              )),
                        ]),
                  ],
                ),
              ),
              ecyConsignmentCommentPage,
            ],
          ),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: _getBottomNavigationBar(),
      ),
    );
  }

  Widget _getBottomNavigationBar() {
    if (_ownerFlag) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        // spacing: 8,
        children: [
          Expanded(
            flex: 1,
            child: SizedBox(
              height: 40.w,
              child: TextButton(
                  onPressed: () async {
                    bool? deleteFlag =
                        await showDeleteConfirmDialog('删除后不可恢复，确定删除吗？');
                    if (deleteFlag != null && deleteFlag) {
                      _deleteConsignProduct();
                    }
                  },
                  style: const ButtonStyle(
                    foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
                    side: WidgetStatePropertyAll(
                        BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
                  ),
                  child: Text(
                    '删除',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 16.sp,
                        color: const Color(0xFF262626) // 设置leading策略
                        ),
                  )),
            ),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              height: 40.w,
              child: TextButton(
                  onPressed: () async {
                    bool? offFlag = await showDeleteConfirmDialog('确定下架吗？');
                    if (offFlag != null && offFlag) {
                      _offlineShelf(_consignProduct.productId!);
                    }
                  },
                  style: const ButtonStyle(
                    foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
                    side: WidgetStatePropertyAll(
                        BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
                  ),
                  child: Text(
                    '下架',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 16.sp,
                        color: const Color(0xFF262626) // 设置leading策略
                        ),
                  )),
            ),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              height: 40.w,
              child: TextButton(
                  onPressed: () async {
                    var logined = await EcyUserUtil.logined();
                    if (logined) {
                      EcyRouter().push(
                          context, EcyRouter.consignmentPublishPage, {
                        "productId": productId
                      }).then((val) => val ? requestData() : null);
                    } else {
                      EcyRouter.push(context, EcyRouter.passwordLoginPage,
                          {EcyRouter.kTargetUrl: EcyRouter.groupPublishPage});
                    }
                  },
                  style: const ButtonStyle(
                    foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                    side: WidgetStatePropertyAll(
                        BorderSide(color: Color(0xFFEA4B9B), width: 0.8)),
                  ),
                  child: Text(
                    '编辑',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 16.sp,
                        color: const Color(0xFFEA4B9B)),
                  )),
            ),
          )
        ],
      );
    }
    var fixFlag = (_consignProduct.status ?? "-1") == "-1";
    if (fixFlag) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            flex: 1,
            child: SizedBox(
              height: 40.w,
              child: TextButton(
                  onPressed: () async {
                    var logined = await EcyUserUtil.logined();
                    if (logined) {
                      EcyRouter().push(context, EcyRouter.consignChatPage, {
                        "consignProduct": _consignProduct
                      }).then((val) => val ? requestData() : null);
                    } else {
                      EcyRouter.push(context, EcyRouter.passwordLoginPage, {EcyRouter.kTargetUrl, ""});
                    }
                  },
                  style: const ButtonStyle(
                    foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                    backgroundColor: WidgetStatePropertyAll(
                        Color.fromARGB(25, 255, 83, 169)),
                    // side: WidgetStatePropertyAll(BorderSide(
                    //     color: Color(0xFFEA4B9B), width: 0.8)),
                  ),
                  child: Text(
                    '联系老师',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 16.sp,
                        color: const Color(0xFFEA4B9B)),
                  )),
            ),
          ),
        ],
      );
    } else {
      return Row(
        // spacing: 10,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            flex: 1,
            child: SizedBox(
              height: 40.w,
              child: TextButton(
                  onPressed: () async {
                    var logined = await EcyUserUtil.logined();
                    if (logined) {
                      EcyRouter().push(context, EcyRouter.consignChatPage, {
                        "consignProduct": _consignProduct
                      }).then((val) => val ?? false ? requestData() : null);
                    } else {
                      EcyRouter.push(context, EcyRouter.passwordLoginPage, {EcyRouter.kTargetUrl: ""});
                    }
                  },
                  style: const ButtonStyle(
                    foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                    backgroundColor: WidgetStatePropertyAll(
                        Color.fromARGB(25, 255, 83, 169)),
                  ),
                  child: Text(
                    '联系老师',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 16.sp,
                        color: const Color(0xFFEA4B9B)),
                  )),
            ),
          ),
          Expanded(
            flex: 1,
            child: Padding(
              padding: const EdgeInsets.only(
                left: 10,
              ),
              child: SizedBox(
                height: 40.w,
                child: TextButton(
                    onPressed: () async {
                      var logined = await EcyUserUtil.logined();
                      if (logined) {
                        bool? confirmFlag = await _showConfirmDialog("确定要下单吗");
                        if (confirmFlag != null && confirmFlag) {
                          _orderCreate();
                        }
                      } else {
                        EcyRouter.push(context, EcyRouter.passwordLoginPage,
                            {EcyRouter.kTargetUrl: ""});
                      }
                    },
                    style: const ButtonStyle(
                      alignment: Alignment.center,
                      side: WidgetStatePropertyAll(
                          BorderSide(color: Color(0xFFEA4B9B), width: 0.8)),
                      backgroundColor:
                          WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                    ),
                    child: const Text(
                      '我想购买',
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                        fontSize: 14,
                        color: Color(0xFFFFFFFF),
                        leadingDistribution:
                            TextLeadingDistribution.even, // 设置leading策略
                      ),
                    )),
              ),
            ),
          )
        ],
      );
    }
  }

  // 弹出对话框
  Future<bool?> showDeleteConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '我再想想',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确定',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }

  /// 评论
  void _groupComment(ConsignComment? commentParent, ConsignReply? reply) async {
    setState(() {
      _consignProduct.commentCount = (_consignProduct.commentCount ?? 0) + 1;
    });

    bool commentFlag = commentParent == null && reply == null;
    if (commentFlag) {
      ConsignComment currConsignComment = ConsignComment();
      currConsignComment.productId = productId;
      currConsignComment.content = _talkController.text;

      try {
        var response = await EcyRequestbasemanager()
            .post("app/api/app/consign/comment", currConsignComment.toJson());
        if (response != null) {
          var commonResponse =
              EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code == 0 || commonResponse.code == 200) {
            currConsignComment = ConsignComment.fromJson(response["data"]);
            ecyConsignmentCommentPage.addComment(currConsignComment);
            return;
          }
          EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
        }
      } catch (e) {
        EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
      }
    } else {
      ConsignReply currConsignReply = ConsignReply();
      currConsignReply.commentId = commentParent?.id;
      currConsignReply.parentReplyId = reply?.id;
      currConsignReply.content = _talkController.text;
      currConsignReply.toUserId = reply?.userId;
      currConsignReply.toUserName = reply?.userName;

      try {
        var response = await EcyRequestbasemanager()
            .post("app/api/app/consign/reply", currConsignReply.toJson());
        if (response != null) {
          var commonResponse =
              EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code == 0 || commonResponse.code == 200) {
            currConsignReply = ConsignReply.fromJson(response["data"]);
            ecyConsignmentCommentPage.addReply(
                commentParent!, currConsignReply);
            return;
          }
          EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
        }
      } catch (e) {
        EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
      }
    }
  }

  // 评价
  void _showModalBottomSheet(BuildContext context,
      ConsignComment? commentParent, ConsignReply? reply) async {
    _talkController.text = "";
    await showModalBottomSheet(
      isScrollControlled: true,
      isDismissible: true, //点击空白处返回功能，默认是true
      enableDrag: true, //是否允许拖动
      elevation: 10,
      backgroundColor: Colors.white, //背景颜色
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      context: context,
      builder: (context) => StatefulBuilder(builder: (context, setState) {
        final keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
        return Padding(
          padding: EdgeInsets.only(bottom: keyboardHeight), //设置底部内边距为软件盘高度
          child: Container(
            constraints: BoxConstraints(
              minHeight: 80, //设置最小高度（必要）
              maxHeight: MediaQuery.of(context).size.height / 1.5, //设置最大高度（必要）
            ),
            padding: const EdgeInsets.only(left: 16, right: 16),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30.w),
                topRight: Radius.circular(30.w),
              ),
              color: Colors.white,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                const Padding(padding: EdgeInsets.only(bottom: 20)),
                TextField(
                  autofocus: true,
                  controller: _talkController,
                  cursorColor: const Color(0x73000000),
                  keyboardType: TextInputType.multiline,
                  decoration: InputDecoration(
                    counterText: '',
                    hintText: commentParent == null
                        ? "请说点什么..."
                        : '回复 @${reply?.userName ?? commentParent?.userName}',
                    hintStyle: const TextStyle(color: Color(0x73000000)),
                    filled: true,
                    fillColor: const Color(0x0A000000),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10.0), // 边框圆角
                      borderSide: BorderSide.none,
                    ),
                  ),
                  maxLength: 500,
                  minLines: 2,
                  maxLines: 10,
                ),
                const Padding(padding: EdgeInsets.only(bottom: 20)),
                SizedBox(
                  height: 45.h,
                  width: 100,
                  child: TextButton(
                      onPressed: () {
                        _groupComment(commentParent, reply);
                        Navigator.pop(context, true);
                      },
                      style: const ButtonStyle(
                        alignment: Alignment.center,
                        backgroundColor:
                            WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                        foregroundColor: WidgetStatePropertyAll(Colors.white),
                      ),
                      child: const Text(
                        '发送',
                        style: TextStyle(
                          height: 1,
                          fontSize: 18,
                          leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                        ),
                      )),
                ),
                const Padding(padding: EdgeInsets.only(bottom: 20)),
              ],
            ),
          ),
        );
      }),
    );
  }

  // 立即下单
  void _showOrderNowModalBottomSheet(BuildContext context) async {
    await showModalBottomSheet(
      isScrollControlled: true,
      isDismissible: true, //点击空白处返回功能，默认是true
      enableDrag: true, //是否允许拖动
      elevation: 10,
      backgroundColor: Colors.white, //背景颜色
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      context: context,
      builder: (context) => StatefulBuilder(builder: (context, setState) {
        final keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
        return Padding(
          padding: EdgeInsets.only(bottom: keyboardHeight), //设置底部内边距为软件盘高度
          child: Container(
            constraints: BoxConstraints(
              minHeight: 80, //设置最小高度（必要）
              maxHeight: MediaQuery.of(context).size.height / 1.5, //设置最大高度（必要）
            ),
            padding: const EdgeInsets.only(left: 16, right: 16),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30.w),
                topRight: Radius.circular(30.w),
              ),
              color: Colors.white,
            ),
            child: const Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[],
            ),
          ),
        );
      }),
    );
  }

  // 弹出对话框
  Future<bool?> _showConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '取消',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: Text(
                            '确认',
                            style: const TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }
}
